﻿using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Model.ReportFilter;
using Kingdee.BOS.Contracts;
using System.Data.SqlClient;
using Kingdee.BOS.Util;
using System.ComponentModel;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
/// <summary>
/// 书名
/// </summary>
/// <remarks>
/// 功能：
/// 创建人：刘雪丽
/// 创建日期：2024-03-19
/// 修改信息（1）：修改人，修改日期，修改内容
/// </remarks>
namespace XZHBBB.k3Cloud.Plugin
{
    [HotUpdate, Description("总账账龄分析表数据读取")]
    public class getAccountAgeBillPlugin : AbstractBillPlugIn
    {
        public override void AfterBindData(EventArgs e)
        {
            base.AfterBindData(e);

        }

        public override void AfterLoadData(EventArgs e)
        {
            base.AfterLoadData(e);

        }

        public override void LoadData(LoadDataEventArgs e)
        {
            base.LoadData(e);
            //复制年份
            this.Model.SetValue("F_RSUS_Year", DateTime.Now.Year);
            ////自动填充当前组织账簿
            //var F_RSUS_OrgIdObj = this.Model.GetValue("F_RSUS_OrgId") as DynamicObject;
            //string F_RSUS_OrgId = "";
            //F_RSUS_OrgId = Convert.ToString(F_RSUS_OrgIdObj?["id"] ?? "0");
            //string strSql = "select fbookid from T_BD_ACCOUNTBOOK where FAccountOrgID=" + F_RSUS_OrgId;
            //DynamicObjectCollection dynamicObjects = DBUtils.ExecuteDynamicObject(this.Context, strSql);
            ////获取账簿id
            //if (dynamicObjects != null && dynamicObjects.Count > 0)
            //{
            //    string fbookid = dynamicObjects[0]["fbookid"].ToString();
            //    this.Model.SetValue("F_RSUS_AccountBook", fbookid);
            //}
        }

        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            if (e.Key.ToUpper() == "F_RSUS_OrgId".ToUpper())
            {
                ////自动填充当前组织账簿
                //var F_RSUS_OrgIdObj = this.Model.GetValue("F_RSUS_OrgId") as DynamicObject;
                //string F_RSUS_OrgId = "";
                //F_RSUS_OrgId = Convert.ToString(F_RSUS_OrgIdObj?["id"]);
                //string strSql = "select fbookid from T_BD_ACCOUNTBOOK where FAccountOrgID=" + F_RSUS_OrgId;
                //DynamicObjectCollection dynamicObjects = DBUtils.ExecuteDynamicObject(this.Context, strSql);
                ////获取账簿id
                //string fbookid = dynamicObjects?[0]["fbookid"].ToString();
                //this.Model.SetValue("F_RSUS_AccountBook", fbookid);
            }
        }
        public override void OnInitialize(InitializeEventArgs e)
        {
            base.OnInitialize(e);


        }
        /// <summary> 
        /// 按钮点击事件
        /// </summary>
        /// <param name="e"></param>
        public override void AfterButtonClick(AfterButtonClickEventArgs e)
        {
            base.AfterButtonClick(e);
            //当点击获取往来账龄时触发
            if (e.Key.ToUpper() == "F_RSUS_getAge".ToUpper())
            {
                //获取过滤条件
                //var F_RSUS_OrgIdObj = this.Model.GetValue("F_RSUS_OrgId") as DynamicObject;
                //string F_RSUS_OrgId = "";
                //if (F_RSUS_OrgIdObj == null)
                //{
                //    this.View.ShowMessage("请先选择组织");
                //    return;
                //}
                //else
                //{
                //    F_RSUS_OrgId = Convert.ToString(F_RSUS_OrgIdObj["id"]);
                //}
                ////获取账簿
                //var F_RSUS_AccountBook = this.Model.GetValue("F_RSUS_AccountBook") as DynamicObject;
                //string F_RSUS_AccountBookid = "";
                //if (F_RSUS_AccountBookid == null)
                //{
                //    this.View.ShowMessage("请先选择账簿");
                //    return;
                //}
                //else
                //{
                //    F_RSUS_AccountBookid = Convert.ToString(F_RSUS_AccountBook["id"]);
                //}
               
                int F_RSUS_Year = Convert.ToInt32(this.Model.GetValue("F_RSUS_Year"));
                if (F_RSUS_Year == 0)
                {
                    this.View.ShowMessage("请先选择年度");
                    return;
                }

                int F_RSUS_Month = Convert.ToInt32(this.Model.GetValue("F_RSUS_Month"));
                if (F_RSUS_Month == 0)
                {
                    this.View.ShowMessage("请先选择月份");
                    return;
                }

                //从总账账龄分析表中获取数据
                GetAccountAge( F_RSUS_Year, F_RSUS_Month);
            }
        }

        /// <summary>
        /// 从总账账龄分析表中获取数据
        /// </summary>
        /// <param name="f_RSUS_OrgId">组织</param>
        /// <param name="f_RSUS_Year">年份</param>
        /// <param name="f_RSUS_Month">月份</param>
        private void GetAccountAge( int f_RSUS_Year, int f_RSUS_Month)
        {
            // throw new NotImplementedException();
            DataTable ftTemp = new DataTable();
            ISysReportService sysReporSservice = ServiceFactory.GetSysReportService(this.Context);
            IPermissionService permissionService = ServiceFactory.GetPermissionService(this.Context);
            //加载字段比较元数据
            var filterMetadata = FormMetaDataCache.GetCachedFilterMetaData(this.Context);
            //加载库存账龄报表元数据。
            var reportMetadata = FormMetaDataCache.GetCachedFormMetaData(this.Context, "GL_AgingSchedule");
            // var reportMetadata = FormMetaDataCache.GetCachedFormMetaData(this.Context, "GL_RPT_AccountingItemsBalance");
            //加载过滤条件元数据。
            var reportFilterMetadata = FormMetaDataCache.GetCachedFormMetaData(this.Context, "GL_AgingScheduleFilter");
            // var reportFilterMetadata = FormMetaDataCache.GetCachedFormMetaData(this.Context, "GL_RPT_AccountingItemsBalanceFilter");
            var reportFilterServiceProvider = reportFilterMetadata.BusinessInfo.GetForm().GetFormServiceProvider();
            //创建报表过滤模型
            var model = new SysReportFilterModel();
            model.SetContext(this.Context, reportFilterMetadata.BusinessInfo, reportFilterServiceProvider);
            model.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
            model.FilterObject.FilterMetaData = filterMetadata;
            model.InitFieldList(reportMetadata, reportFilterMetadata);
            model.GetSchemeList();
            //获取过滤方案，可以通过LoadScheme("Id")，查询报表默认存在的一些过滤方案
            //SELECT * FROM T_BAS_FILTERSCHEME  where fschemename='账龄取数误删'
            var entity = model.Load("65f9007b10d7f6");
            var filter = model.GetFilterParameter();
            string ftime = ""; DateTime dateTime;
            //设置日期、核算组织
            if (Convert.ToInt32(f_RSUS_Month) < 12)
            {
                ftime = f_RSUS_Year + "-" + (f_RSUS_Month + 1) + "-01";
                dateTime = Convert.ToDateTime(ftime).AddDays(-1);
            }
            else
            {
                ftime = f_RSUS_Year + "-" + "12-31";
                dateTime = Convert.ToDateTime(ftime);
            }
            filter.CustomFilter["DeadLine"] = dateTime;
            //filter.CustomFilter["Book_id"] = Convert.ToInt32(faccoutbookid["id"]);//账簿
            //filter.CustomFilter["Book"] = faccoutbookid;//账簿
            //filter.CustomFilter["FMUTILACCTBOOKID"] = faccoutbookid;
            //filter.CustomFilter["FMUTILACCTBOOKID"] = "";//账簿
            //报表参数
            IRptParams p = new RptParams();
            p.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
            p.StartRow = 1;
            // StartRow和EndRow是报表数据分页的起始行数和截至行数，
            //一般取所有数据，所以EndRow取int最大值。
            p.EndRow = int.MaxValue;
            p.FilterParameter = filter;
            p.FilterFieldInfo = model.FilterFieldInfo;
            p.BaseDataTempTable.AddRange(permissionService.GetBaseDataTempTable(this.Context, reportMetadata.BusinessInfo.GetForm().Id));
            #region 新建表
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("fdate", typeof(DateTime));//记账日期
            dtResult.Columns.Add("fwriteTime", typeof(DateTime));//获取日期
            dtResult.Columns.Add("FACCOUNTBOOKID", typeof(string));//账簿id
            dtResult.Columns.Add("fbooknumber", typeof(string));//账簿编码
            dtResult.Columns.Add("fbookname", typeof(string));//账簿名称
            dtResult.Columns.Add("FACCOUNTID", typeof(string));//科目id
            dtResult.Columns.Add("FACCTNUMBER", typeof(string));//科目编码
            dtResult.Columns.Add("FACCTNAME", typeof(string));//科目名称
            dtResult.Columns.Add("fflex4", typeof(string));//供应商-名称
            dtResult.Columns.Add("FFLEX6", typeof(string));//客户-编码
            //dtResult.Columns.Add("FDAYS", typeof(decimal));//账龄
            dtResult.Columns.Add("FCURRENCYID", typeof(string));//币别
            dtResult.Columns.Add("FCURRENCYNAME", typeof(string));//币别名称
            dtResult.Columns.Add("FRESERVEDFOR", typeof(decimal));//
            dtResult.Columns.Add("FRESERVED", typeof(decimal));
            dtResult.Columns.Add("F365FOR", typeof(decimal));
            dtResult.Columns.Add("F365", typeof(decimal));
            dtResult.Columns.Add("F730FOR", typeof(decimal));
            dtResult.Columns.Add("F730", typeof(decimal));
            dtResult.Columns.Add("F1095FOR", typeof(decimal));
            dtResult.Columns.Add("F1095", typeof(decimal));
            dtResult.Columns.Add("F1460FOR", typeof(decimal));
            dtResult.Columns.Add("F1460", typeof(decimal));
            dtResult.Columns.Add("F1825FOR", typeof(decimal));
            dtResult.Columns.Add("F1825", typeof(decimal));
            dtResult.Columns.Add("F1826FOR", typeof(decimal));
            dtResult.Columns.Add("F1826", typeof(decimal));
            dtResult.Columns.Add("F2147483647FOR", typeof(decimal));
            dtResult.Columns.Add("F2147483647", typeof(decimal));
            #endregion
            MoveReportServiceParameter param = new MoveReportServiceParameter(this.Context, reportMetadata.BusinessInfo, Guid.NewGuid().ToString(), p);
            //简单账表使用GetReportData方法 
            using (DataTable dt = sysReporSservice.GetCrossReportData(param).DataSource)
            {
                #region 将数据复制到dtResult
                foreach (DataRow item in dt.Rows)
                {

                    DataRow drw = dtResult.NewRow();
                    drw["fdate"] = dateTime;
                    drw["fwriteTime"] = DateTime.Now;
                    drw["FACCOUNTBOOKID"] = item["FACCOUNTBOOKID"];
                    drw["fbooknumber"] = item["fbooknumber"];
                    drw["fbookname"] = item["fbookname"];//
                    drw["FACCOUNTID"] = item["FACCOUNTID"];//
                    drw["FACCTNUMBER"] = item["FACCTNUMBER"];//
                    drw["FACCTNAME"] = item["FACCTNAME"];
                    drw["fflex4"] = item["fflex4"];//
                    drw["FFLEX6"] = item["FFLEX6"];//
                    //drw["FDAYS"] = item["FDAYS"];//
                    drw["FCURRENCYID"] = item["FCURRENCYID"];
                    drw["FCURRENCYNAME"] = item["FCURRENCYNAME"];//
                    drw["FRESERVEDFOR"] = item["FRESERVEDFOR"];//
                    drw["FRESERVED"] = item["FRESERVED"];//
                    drw["F365FOR"] = item["F365FOR"];
                    drw["F365"] = item["F365"];//
                    drw["F730FOR"] = item["F730FOR"];//
                    drw["F730"] = item["F730"];
                    drw["F1095FOR"] = item["F1095FOR"];//
                    drw["F1095"] = item["F1095"];//
                    drw["F1460FOR"] = item["F1460FOR"];//
                    drw["F1460"] = item["F1460"];
                    drw["F1825FOR"] = item["F1825FOR"];//
                    drw["F1825"] = item["F1825"];//
                    drw["F1826FOR"] = item["F1826FOR"];//
                    drw["F1826"] = item["F1826"];//
                    drw["F2147483647FOR"] = item["F2147483647FOR"];//
                    drw["F2147483647"] = item["F2147483647"];//
                    dtResult.Rows.Add(drw);

                }
                #endregion
                ServiceFactory.CloseService(sysReporSservice);
                ServiceFactory.CloseService(permissionService);
            }
            //将数据存到数据表实体表中
            string connectionString = "Data Source=.;database=AISLH;Uid=sa;Pwd=1234500;";
            SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            sqlbulkcopy.DestinationTableName = "dev_t_accountAge";//数据库中的自己创建表名:临时表名
            sqlbulkcopy.WriteToServer(dtResult);
            //this.View.ShowMessage("获取成功");
            //Button button= this.View.GetControl<Button>("F_Dev_Year");//年
            //button.SetCustomPropertyValue("value", "获取成功");
            //button.SetCustomPropertyValue("disabled", true);

        }

        /// <summary>
        /// 构建基础资料数据包
        /// </summary>
        /// <param name="formId"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        private DynamicObject LoadBDObject(string formId, string number)
        {
            FormMetadata meta = MetaDataServiceHelper.Load(this.Context, formId) as FormMetadata;
            // 构建查询参数，设置过滤条件   
            QueryBuilderParemeter queryParam = new QueryBuilderParemeter();
            queryParam.FormId = formId;
            queryParam.BusinessInfo = meta.BusinessInfo;
            queryParam.FilterClauseWihtKey = string.Format(" {0} = '{1}' ", meta.BusinessInfo.GetForm().NumberFieldKey, number);
            var bdObjs = BusinessDataServiceHelper.Load(this.Context, meta.BusinessInfo.GetDynamicObjectType(), queryParam);
            return bdObjs[0];
        }
    }
}
